import re
import json
import os
from datetime import datetime


def validate_email(email):
    """
    验证邮箱格式是否正确
    """
    pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
    return bool(re.match(pattern, email))


def validate_phone(phone):
    """
    验证手机号格式是否正确（简化版，支持中国大陆手机号）
    """
    pattern = r'^1[3-9]\d{9}$'
    return bool(re.match(pattern, phone))


def validate_password(password):
    """
    验证密码强度
    要求:至少8位,包含字母和数字
    """
    if len(password) < 8:
        return False, "密码长度至少8位"
    if not re.search(r'[a-zA-Z]', password):
        return False, "密码必须包含字母"
    if not re.search(r'[0-9]', password):
        return False, "密码必须包含数字"
    return True, "密码强度符合要求"


def format_datetime(dt):
    """
    格式化日期时间
    """
    if isinstance(dt, str):
        return dt
    return dt.strftime('%Y-%m-%d %H:%M:%S')


def calculate_discount(original_price, discount_percentage):
    """
    计算折扣后的价格
    """
    discount_amount = original_price * (discount_percentage / 100)
    return original_price - discount_amount


def generate_unique_id(prefix=""):
    """
    生成唯一ID
    """
    import uuid
    return f"{prefix}{str(uuid.uuid4())[:8]}"


def validate_address(address):
    """
    验证地址信息
    """
    required_fields = ['province', 'city', 'district', 'detail_address', 'zip_code', 'contact_name', 'contact_phone']
    for field in required_fields:
        if field not in address or not address[field]:
            return False, f"缺少必要的地址字段: {field}"
    
    # 验证联系电话
    if not validate_phone(address['contact_phone']):
        return False, "联系电话格式不正确"
    
    return True, "地址信息有效"


def calculate_total_price(items):
    """
    计算商品总价
    items: [{"product": Product对象, "quantity": int}, ...]
    """
    total = 0
    for item in items:
        total += item['product'].price * item['quantity']
    return total


def export_to_json(data, file_path):
    """
    导出数据到JSON文件
    """
    try:
        with open(file_path, 'w', encoding='utf-8') as f:
            json.dump(data, f, ensure_ascii=False, indent=2)
        return True
    except Exception as e:
        print(f"导出JSON文件失败: {e}")
        return False


def import_from_json(file_path):
    """
    从JSON文件导入数据
    """
    try:
        with open(file_path, 'r', encoding='utf-8') as f:
            return json.load(f)
    except FileNotFoundError:
        print(f"文件不存在: {file_path}")
        return None
    except json.JSONDecodeError:
        print(f"JSON解析错误: {file_path}")
        return None


def ensure_directory(directory):
    """
    确保目录存在，如果不存在则创建
    """
    if not os.path.exists(directory):
        os.makedirs(directory)


def get_file_size(file_path):
    """
    获取文件大小（字节）
    """
    if os.path.exists(file_path):
        return os.path.getsize(file_path)
    return 0


def get_file_extension(filename):
    """
    获取文件扩展名
    """
    return os.path.splitext(filename)[1].lower()


def validate_image_file(filename):
    """
    验证是否为图片文件
    """
    allowed_extensions = ['.jpg', '.jpeg', '.png', '.gif', '.bmp']
    extension = get_file_extension(filename)
    return extension in allowed_extensions


def sanitize_filename(filename):
    """
    清理文件名，移除特殊字符
    """
    # 移除或替换不安全的字符
    return re.sub(r'[\\/:*?"<>|]', '_', filename)


def calculate_shipping_fee(order_amount, shipping_method="standard"):
    """
    计算运费
    """
    shipping_fees = {
        "standard": 10,  # 标准配送
        "express": 20,  #  express配送
        "same_day": 30  # 当天达
    }
    
    # 订单金额满99免运费
    if order_amount >= 99:
        return 0
    
    return shipping_fees.get(shipping_method, 10)


def calculate_tax(amount, tax_rate=0.13):
    """
    计算税费
    """
    return amount * tax_rate


def format_price(price):
    """
    格式化价格显示
    """
    return f"¥{price:.2f}"


def truncate_text(text, max_length=100):
    """
    截断文本
    """
    if len(text) <= max_length:
        return text
    return text[:max_length] + "..."


def get_status_color(status):
    """
    根据订单状态返回对应的颜色
    """
    status_colors = {
        "Pending": "#FFA500",  # 橙色
        "Processing": "#007BFF",  # 蓝色
        "Shipped": "#28A745",  # 绿色
        "Delivered": "#17A2B8",  # 青色
        "Cancelled": "#DC3545"  # 红色
    }
    return status_colors.get(status, "#6C757D")  # 默认灰色


def generate_report(data, report_type="sales"):
    """
    生成简单的报表数据
    """
    if report_type == "sales":
        # 销售报表
        total_sales = sum(item.get('amount', 0) for item in data)
        total_orders = len(data)
        avg_order_value = total_sales / total_orders if total_orders > 0 else 0
        
        return {
            "total_sales": total_sales,
            "total_orders": total_orders,
            "average_order_value": avg_order_value
        }
    
    return None


def search_by_keyword(items, keyword, fields=None):
    """
    根据关键词搜索项目
    """
    if not fields:
        # 默认搜索对象的所有字符串属性
        results = []
        for item in items:
            for attr, value in item.__dict__.items():
                if isinstance(value, str) and keyword.lower() in value.lower():
                    results.append(item)
                    break
        return results
    else:
        # 按指定字段搜索
        results = []
        for item in items:
            for field in fields:
                if hasattr(item, field):
                    value = getattr(item, field)
                    if isinstance(value, str) and keyword.lower() in value.lower():
                        results.append(item)
                        break
        return results